<?php


namespace App\Http\Controllers;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use phpDocumentor\Reflection\Types\Object_;

class BaseController extends Controller
{
    const OK = 200; //成功
    const UNAUTHORIZED = 401; //无权限
    const REQUIRED_FIELD_EMPTY = 422; //必填字段为空
    const NOTFOUND = 404; //无数据

    public function returnJson($code = 200, $msg = '', $data = []){
        $result =[
            'Status Code' => $code,
            'Body' => [
                'msg'   =>  $msg,
                'data'  =>  $data
            ]
        ];
        return response($result);
    }

    /**
     * 验证器
     * @param $params
     * @param $rules
     * @return bool
     */
    public function validationParams($params, $rules){
        //设置验证规则
        $validator = Validator::make($params, $rules);

        //判断输入的凭证是否错误
        if ($validator->fails()) {
            return true;
        }
        return false;
    }

    /**
     * 上传文件
     * @param Request $request
     * @param $uploadName
     * @param string $contents
     * @param string[] $rule
     * @return bool|false|string
     */
    public function uploadFile(Request $request, $uploadName, $contents = 'employeeImg', $rule = ['jpg', 'jpeg', 'png']){
        $file = $request->file($uploadName);
        if ($file->isValid()){
            //判断类型
            $extension = $file->getClientOriginalExtension();
            if (!in_array($extension, $rule)){
                return false;
            }

            //移动图片
            $file_path = md5(time() . $file->getClientOriginalName()) . '.' . $extension;
            $url = $file->storeAs($contents, $file_path);
            return $url;
        }
        return false;
    }
}
